package com.raincat.tools.multimediapickertools;

import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.raincat.tools.R;
import com.raincat.tools.multimediapickertools.subscaleview.ImageSource;
import com.raincat.tools.multimediapickertools.subscaleview.ImageViewState;
import com.raincat.tools.multimediapickertools.subscaleview.SubsamplingScaleImageView;
import com.raincat.tools.multimediapickertools.utils.LazyLoadFragment;
import com.raincat.tools.multimediapickertools.utils.MultiMediaItem;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;


/**
 * <pre>
 *     author : RainCat
 *     org    : Shenzhen JingYu Network Technology Co., Ltd.
 *     e-mail : nining377@gmail.com
 *     time   : 2018/04/24
 *     desc   : 图片浏览
 *     version: 1.0
 * </pre>
 */

public class PicturesBrowseFragment extends LazyLoadFragment {
    private Context context;
    private static final String BUNDLE_URI = "uri";

    private SubsamplingScaleImageView subsamplingScaleImageView;
    private GifImageView gifImageView;
    private GifDrawable gifDrawable;
    private TextView textView;

    private MultiMediaItem multiMediaItem;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (multiMediaItem == null && savedInstanceState.containsKey(BUNDLE_URI)) {
                multiMediaItem = (MultiMediaItem) savedInstanceState.getSerializable(BUNDLE_URI);
            }
        }
        View view = inflater.inflate(R.layout.picker_fragment_picturesbrowse, container, false);
        subsamplingScaleImageView = view.findViewById(R.id.SubsamplingScaleImageView);
        subsamplingScaleImageView.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
        gifImageView = view.findViewById(R.id.GifImageView);
        textView = view.findViewById(R.id.tv_error);
        return view;
    }

    void setMultiMediaItem(MultiMediaItem multiMediaItem) {
        this.multiMediaItem = multiMediaItem;
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible) {
            if (gifDrawable != null)
                gifDrawable.start();
        } else {
            if (gifDrawable != null)
                gifDrawable.pause();
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        if (multiMediaItem.path != null) {
            if (multiMediaItem.suffix.equalsIgnoreCase("gif")) {
                try {
                    gifDrawable = new GifDrawable(multiMediaItem.path);
                    gifImageView.setImageDrawable(gifDrawable);
                    gifDrawable.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (multiMediaItem.outHeight == 0 || multiMediaItem.outWidth == 0) {
                textView.setVisibility(View.VISIBLE);
            } else {
                float scale = getInitImageScale(multiMediaItem.path);
                subsamplingScaleImageView.setMaxScale(scale + 2.0f);
                subsamplingScaleImageView.setImage(ImageSource.uri(multiMediaItem.path), new ImageViewState(scale, new PointF(0, 0), SubsamplingScaleImageView.ORIENTATION_USE_EXIF));
            }
        }
    }

    private float getInitImageScale(String imagePath) {
        float scale = 1.0f;
        try {
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(imagePath)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            // 拿到图片的宽和高
            int dw = options.outWidth;
            scale = getPhoneW() * 1.0f / dw;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return scale;
    }

    private int getPhoneW() {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }

    @Override
    public void onDestroyView() {
        multiMediaItem = null;
        if (subsamplingScaleImageView != null) {
            subsamplingScaleImageView.recycle();
            subsamplingScaleImageView = null;
        }
        if (gifDrawable != null) {
            gifDrawable.stop();
            gifDrawable.recycle();
            gifDrawable = null;
            gifImageView = null;
        }
        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        View rootView = getView();
        if (rootView != null) {
            outState.putSerializable(BUNDLE_URI, multiMediaItem);
        }
    }
}
